﻿namespace Hidistro.UI.Web.Pay
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Hidistro.UI.Common.Controls;
using Hidistro.Messages;
using Hidistro.Membership.Core.Enums;
using Hidistro.Membership.Core;
using Hidistro.Membership.Context;
using Hidistro.SaleSystem.Member;
using Hidistro.Entities.Orders;
using Hidistro.Core;
using Hidistro.Entities.Promotions;
using Hidistro.SaleSystem.Shopping;
using System.Collections.Specialized;
using Hishop.Plugins;
    using System.Web.Configuration;
    using System.IO;
    using System.Text;

    public class YL_OrderRet_url : Page
    {
        protected decimal Amount;
        protected string Gateway;
        protected PaymentNotify Notify;
        //protected OrderInfo Order;
        protected OrderInfo Orders;
        protected JSShop.Model.OrderInfo Order;
        protected string OrderId;




        private void FinishOrder()
        {
            if (this.Order.OrderStatus == JSShop.Enum.OrderStatus.Finished)
            {
                base.Page.Response.Write(string.Format("<p style=\"font-size:16px;\">恭喜您，订单已成功完成支付：{0}</br>支付金额：{1}</p>", this.OrderId, this.Amount.ToString("F")));
            }
            else if (this.Orders.CheckAction(OrderActions.BUYER_CONFIRM_GOODS) && TradeHelper.ConfirmOrderFinish(this.Order))
            {
                base.Page.Response.Write(string.Format("<p style=\"font-size:16px;\">恭喜您，订单已成功完成支付：{0}</br>支付金额：{1}</p>", this.OrderId, this.Amount.ToString("F")));
            }
            else
            {
                base.Page.Response.Write(string.Format("<p style=\"font-size:16px;color:#ff0000;\">订单支付已成功，但是系统在处理过程中遇到问题，请联系管理员</br>支付金额：{0}</p>", this.Amount.ToString("F")));
            }
        }

        private void Notify_Finished(object sender, FinishedEventArgs e)
        {
            if (e.IsMedTrade)
            {
                this.FinishOrder();
            }
            else
            {
                this.UserPayOrder();
            }
        }

        private void Notify_NotifyVerifyFaild(object sender, EventArgs e)
        {
            base.Page.Response.Write("<p style=\"font-size:16px;\">签名验证失败，可能支付密钥已经被修改</p>");
        }

        private void Notify_Payment(object sender, EventArgs e)
        {
            this.UserPayOrder();
        }

        protected void CreateLog(string strtype, string[] myStrArr)
        {
            StringBuilder str = new StringBuilder();
            str.Append("\r\n" + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
            str.Append("\r\n.支付信息：");
            string ip = "";
            if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
            {
                ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
            }
            else
            {
                ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
            }
            str.Append("\r\n\tIp:" + ip);
            str.Append("\r\n\t页面：" + Request.Url.ToString());
            str.Append("\r\n\t数据方向：" + strtype);
            str.Append("\r\n\t数据内容如下："  + "\r\n");
            for (int i = 0; i < myStrArr.Length; i++)
            {
                str.Append(" | " + myStrArr[i]);               
            }
            str.Append("\r\n--------------------------------------------------------------------------------------------------");
            str.Append("\r\n--------------------------------------------------------------------------------------------------");
            string upLoadPath = WebConfigurationManager.AppSettings["PayLogPath"];
            if (!Directory.Exists(upLoadPath))
            {
                Directory.CreateDirectory(upLoadPath);
            }
            string FileName;
            string[] flist = Directory.GetFiles(upLoadPath, DateTime.Now.ToString("yyyy.MM.dd") + "_?.log");
            if (flist != null && flist.Length > 0)
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + flist.Length.ToString() + ".log";
                FileInfo fileInfo = new FileInfo(FileName);
                if (fileInfo != null && fileInfo.Length >= 100 * 1024 * 1024)
                {
                    FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_" + (flist.Length + 1).ToString() + ".log";
                }
            }
            else
            {
                FileName = upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + "_1.log";
            }
            File.AppendAllText(FileName, str.ToString(), Encoding.UTF8);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Order = new JSShop.Model.OrderInfo();
            base.Page.Response.Write("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"/>");
            NameValueCollection values2 = new NameValueCollection();
            values2.Add(this.Page.Request.Form);
            values2.Add(this.Page.Request.QueryString);
            NameValueCollection parameters = values2;
            String[] myStrArr = new String[parameters.Count];
            values2.CopyTo(myStrArr, 0);
           // CreateLog("银行返回数据",myStrArr);
            this.Gateway = "wp_bankunionrequest";
            this.OrderId = myStrArr[1];
            string orderst = myStrArr[6];
            //this.Order = ShoppingProcessor.GetOrderInfo(this.OrderId);
            this.Order = new Juse.Interface.OrderInterface().GetOrderInfo(this.OrderId);
            Amount = Order.GetAmount();
            if (this.Order == null)
            {

                base.Response.Write(string.Format("找不到对应的订单，你付款的订单可能已经被删除 订单状态:" + Order.OrderStatus));

            }
            else
            {
                //if (this.Order.OrderStatus == JSShop.Enum.OrderStatus.BuyerAlreadyPaid)
                //{
                if (this.Order.IsAlreadyPay == 1)
                {
                    bool tj = TradeHelper.UserPayOrder(this.Order, true);
                    if(tj)
                    base.Response.Write(string.Format("<p style=\"font-size:16px;\">恭喜您，订单已成功完成支付：{0}</br>支付金额：{1}</p>", this.OrderId, this.Amount.ToString("F")));
                    else
                    {
                        base.Response.Write(string.Format("订单ID:" + OrderId + "订单已支付成功，但服务器网络连接问题：请联系管理员！订单状态:" + this.Order.OrderStatus));
 
                    }
                }
                else
                {
                    if (orderst == "1001")
                    {
                        bool reta = TradeHelper.UserPayOrder(this.Order, true);
                        if (reta)
                        {
                            base.Response.Write(string.Format("<p style=\"font-size:16px;\">恭喜您，订单已成功完成支付：{0}</br>支付金额：{1}</p>", this.OrderId, this.Amount.ToString("F")));

                        }
                        else
                        {
                            base.Response.Write(string.Format("订单ID:" + OrderId + "订单数据查询系统出现错误：请联系管理员！订单状态:" + this.Order.OrderStatus));

                        }

                    }
                    else
                    {
                        base.Response.Write(string.Format("订单ID:" + OrderId + "银联返回的订单状态有误：请联系管理员！订单状态:" + this.Order.OrderStatus));
                    }

                }

            }
        }

        private void UserPayOrder()
        {
            int maxCount = 0;
            int orderCount = 0;
            int groupBuyOerderNumber = 0;
            if (this.Order.GroupBuyId > 0)
            {
                GroupBuyInfo groupBuy = TradeHelper.GetGroupBuy(this.Order.GroupBuyId);
                if ((groupBuy == null) || (groupBuy.Status != GroupBuyStatus.UnderWay))
                {
                    base.Page.Response.Write("<p style=\"font-size:16px;\">订单为团购订单，团购活动已结束，支付失败</p>");
                    return;
                }
                orderCount = TradeHelper.GetOrderCount(this.Order.GroupBuyId);
                groupBuyOerderNumber = this.Orders.GetGroupBuyOerderNumber();
                maxCount = groupBuy.MaxCount;
                if (maxCount < (orderCount + groupBuyOerderNumber))
                {
                    base.Page.Response.Write("<p style=\"font-size:16px;\">订单为团购订单，订购数量超过订购总数，支付失败</p>");
                    return;
                }
            }
            if (this.Orders.CheckAction(OrderActions.BUYER_PAY) && TradeHelper.UserPayOrder(this.Order, false))
            {
                DebitNoteInfo note = new DebitNoteInfo
                {
                    NoteId = Globals.GetGenerateId(),
                    OrderId = this.Order.OrderId,
                    Operator = this.Order.Username,
                    Remark = "客户订单在线支付成功"
                };
                TradeHelper.SaveDebitNote(note);
                if ((this.Order.GroupBuyId > 0) && (maxCount == (orderCount + groupBuyOerderNumber)))
                {
                    TradeHelper.SetGroupBuyEndUntreated(this.Order.GroupBuyId);
                }
                if ((this.Order.UserId != 0) && (this.Order.UserId != 0x44c))
                {
                    IUser user = Users.GetUser(this.Order.UserId);
                    if ((user != null) && (user.UserRole == UserRole.Member))
                    {
                        Messenger.OrderPayment(user, this.Order.OrderId, this.Order.GetTotal());
                    }
                }
                Amount = Order.GetAmount();
                this.Orders.OnPayment();
                base.Page.Response.Write(string.Format("<p style=\"font-size:16px;\">恭喜您，订单已成功完成支付：{0}</br>支付金额：{1}</p>", this.OrderId, this.Amount.ToString("F")));
            }
            else
            {
                base.Page.Response.Write(string.Format("<p style=\"font-size:16px;color:#ff0000;\">订单支付已成功，但是系统在处理过程中遇到问题，请联系管理员</br>支付金额：{0}</p>", this.Amount.ToString("F")));
            }
            //}
        }


    }
}
